<template>
  <div id="cardDetails">
        <div>
            <el-card class="box-card">
                <el-row>
                    <el-col :span="8"> 
                        <el-input
                        placeholder="请输入会员卡名称"
                        v-model="cardName"
                        clearable>
                        </el-input>
                    </el-col>
                    <el-col :span="2" :offset="1"><el-button icon="el-icon-search" @click="getCardDetailsByPage" circle></el-button></el-col>
                    <el-col :span="2"><el-button type="primary" @click="saveCardDetail" round>新增</el-button></el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="24">
                        <el-table
                            :data="productData"
                            border
                            style="width:100%">
                            <el-table-column
                            fixed
                            prop="id"
                            label="序号"
                            >
                            </el-table-column>
                            <el-table-column
                            prop="cardName"
                            label="会员卡名称"
                            >
                            </el-table-column>
                            <el-table-column
                            prop="price"
                            label="会员卡价格"
                            >
                            </el-table-column>
                            <el-table-column
                            prop="purchaseMonth"
                            label="月份"
                            >
                            </el-table-column>
                            <el-table-column
                            fixed="right"
                            label="操作"
                            width="200">
                            <template slot-scope="scope">
                                <el-button @click="handleClick(scope.row)" type="text" size="small" >查看</el-button>
                                <el-button @click="handleUpdate(scope.row)" type="text" size="small">编辑</el-button>
                                <el-button @click="deleteCardDetails(scope.row)" type="text" size="small" style="color: red;">删除</el-button>
                            </template>
                            </el-table-column>
                        </el-table>
                    </el-col>
                </el-row>
                <el-row style="text-align: center;">
                    <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage4"
                    :page-sizes="[10, 20, 30, 40]"
                    :page-size="10"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="page.total">
                    </el-pagination>          
                </el-row>
            </el-card>
            <!-- 数据新增弹窗 -->
            <el-dialog title="新增会员卡" :visible.sync="dialogFormVisible" @close="handleClose('productForm')">
                <el-form :model="productForm" :rules="rules" ref="productForm">
                    <el-form-item label="会员卡名称" :label-width="formLabelWidth" prop="cardName">
                        <el-select v-model="productForm.cardId" placeholder="请选择" >
                            <el-option
                            v-for="item in selectCard"
                            :key="item.id"
                            :label="item.cardName"
                            :value="item.id"
                            @click.native="choiceName(item.cardName,item.id)">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="会员卡月份" :label-width="formLabelWidth" prop="purchaseMonth">
                        <el-input v-model="productForm.purchaseMonth"  placeholder="请输入月份(限数字)" autocomplete="off"  oninput="value=value.replace(/[^0-9]/g,'')" ></el-input>
                    </el-form-item>
                    <el-form-item label="会员卡价格" :label-width="formLabelWidth" prop="price">
                        <el-input v-model.number="productForm.price"  placeholder="请输入价钱(限数字)" autocomplete="off"  oninput="value=value.replace(/[^0-9]/g,'')" ></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveCardDetails('productForm')">确 定</el-button>
                </div>
            </el-dialog>
            <!-- 数据查看弹窗 -->
            <el-dialog title="查看详情" :visible.sync="dialogFormVisibleDatil">
                <el-form :model="productFormList">
                    <el-form-item label="会员卡名称" :label-width="formLabelWidth" prop="cardName">
                        <el-input v-model="productFormList.cardName" autocomplete="off" :disabled="true"></el-input>
                    </el-form-item>
                    <el-form-item label="会员卡月份" :label-width="formLabelWidth" prop="cardNumber">
                        <el-input v-model="productFormList.purchaseMonth" autocomplete="off" :disabled="true"></el-input>
                    </el-form-item>
                    <el-form-item label="会员卡价格" :label-width="formLabelWidth" prop="cardPrice">
                        <el-input v-model.number="productFormList.price"  placeholder="请输入数字(限数字)" autocomplete="off"  oninput="value=value.replace(/[^0-9]/g,'')" :disabled="true" ></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisibleDatil = false">关闭</el-button>
                </div>
            </el-dialog>
            <!-- 数据修改弹窗 -->
            <el-dialog title="会员卡编辑" :visible.sync="dialogFormVisibleUpdate" @close="handleEditClose('productFormEdit')">
                <el-form :model="productFormEdit" :rules="rulesEdit" ref="productFormEdit">
                    <el-form-item label="会员卡名称" :label-width="formLabelWidth" prop="cardName">
                    <el-select v-model="productFormEdit.cardId" placeholder="请选择" >
                        <el-option
                        v-for="item in selectCard"
                        :key="item.id"
                        :label="item.cardName"
                        :value="item.id"
                        @click.native="choiceName(item.cardName,item.id)">
                        </el-option>
                    </el-select>
                    </el-form-item>
                    <el-form-item label="会员卡月份" :label-width="formLabelWidth" prop="purchaseMonth">
                        <el-input v-model="productFormEdit.purchaseMonth"  placeholder="请输入月份(限数字)" autocomplete="off"  oninput="value=value.replace(/[^0-9]/g,'')" ></el-input>
                    </el-form-item>
                    <el-form-item label="会员卡价格" :label-width="formLabelWidth" prop="price">
                        <el-input v-model.number="productFormEdit.price"  placeholder="请输入价钱(限数字)" autocomplete="off"  oninput="value=value.replace(/[^0-9]/g,'')" ></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisibleUpdate = false">取 消</el-button>
                    <el-button type="primary" @click="updateCardDetails('productFormEdit')">确 定</el-button>
                </div>
            </el-dialog>
        </div>
  </div>
</template>

<script>
const axios = require('axios');
export default {
   name: 'cardDetails',
        data(){
            //校验新增中会员卡名称是否为空或者名称是否正确或者是否重复
            var cardName = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入会员卡名称'));
                }else{
                    callback();
                }
            };
            //校验新增中会员卡月份是否为空或者月份是否已录入
            var purchaseMonth = (rule, value, callback) => {
                if(value === ''){
                     callback(new Error('请输入会员卡月份'));
                }
                else {
                    this.saveValue=value-0
                    axios.get("http://127.0.0.1:8082/cardDetails/selectCardDetailsPurchaseMonth?purchaseMonth=" + value + "&cardId=" + this.choiceCardId).then(res=>{
                        this.selectMonthList=res.data.obj
                        this.selectMonthList.forEach((item)=>{
                            this.selectPurchaseMonth=item.purchaseMonth
                        })
                        if (this.saveValue !== this.selectPurchaseMonth) {
                            callback();
                            this.selectPurchaseMonth=''
                        } else {
                            callback(new Error('该月份已录入'));
                            this.selectPurchaseMonth=''
                        }
                    })
                }
            };
            //新增校验会员卡价钱不能为空不能为零
            var price = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入会员卡价钱'));
                }else if (value === 0) {
                    callback(new Error('会员卡价钱不能为零'));
                }
                else{
                    callback();
                }
            };
            //校验修改月份是否为空输入的月份是否重复录入
            var purchaseMonthEdit = (rule, value, callback) => {
                this.saveValue=value-0
                if( value===''){
                     callback(new Error('请输入会员卡月份'));
                }else if(this.updatePurchaseMont === this.saveValue){
                    callback();
                }else{
                    if(this.updatePurchaseMont !== this.saveValue){
                        axios.get("http://127.0.0.1:8082/cardDetails/selectCardDetailsPurchaseMonth?purchaseMonth=" + value + "&cardId=" + this.productFormEdit.cardId).then(res=>{
                            this.selectMonthList=res.data.obj
                            this.selectMonthList.forEach((item)=>{
                                this.selectPurchaseMonth=item.purchaseMonth
                            })
                            if (this.saveValue !== this.selectPurchaseMonth) {
                                callback();
                                this.selectPurchaseMonth=''
                            } else {
                                callback(new Error('该月份已录入'));
                                this.selectPurchaseMonth=''
                            }
                        })
                    }
                }
            }; 
            //修改校验会员卡价钱不能为空不能为零
            var priceEdit = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入会员卡价钱'));
                }else if (value === 0) {
                    callback(new Error('会员卡价钱不能为零'));
                }else{
                    callback();
                }
            };
            return {
                updatePurchaseMont:'', //点击边境按钮使将获取到的月份数放进变量用于修改校验判断
                choiceCardId:'',  //新增弹框选择卡类型是获取id放进变量用于新增校验判断
                saveValue:'',  //新增修改校验存放转换值
                selectPurchaseMonth:[],//新增月份数校验查询遍历结果
                selectMonthList:[],//新增月份数校验查询结果集合
                selectCard:[],//查询会员卡类型结果集合
                cardName:'',//分页模糊查查询字段（会员卡名称）
                checkCardName:'',//新增校验会员卡名是否重复查询结果名称
                cardNameList:[],//新增校验会员卡名是否重复查询结果集合
                productData: [],//分页全查存放的数组
                dialogFormVisible: false,//新增弹框true弹出
                dialogFormVisibleDatil:false,//查看弹框true弹出
                dialogFormVisibleUpdate:false,//修改弹框true弹出
                productForm: {// 新增时使用到的form对象
                    id:'', //会员卡id
                    cardName:'', //会员卡名称
                    price:'', //会员卡价格
                    purchaseMonth:'', //会员卡月份
                    cardId:'',
                },
                productFormList:{//查看时使用到的form对象
                    id:'', //会员卡id
                    cardName:'', //会员卡名称
                    price:'', //会员卡价格
                    purchaseMonth:'', //会员卡月份
                    cardId:'',
                },
                productFormEdit:{// 修改时使用到的form对象
                    id:'', //会员卡id
                    cardName:'', //会员卡名称
                    price:'', //会员卡价格
                    purchaseMonth:'', //会员卡月份
                    cardId:'',
                },
                cardForm:{
                    id:'',
                    cardName:'',
                    cardLevel:'',
                },
                formLabelWidth: '120px',
                currentPage4: 1,//分页当前选中页
                page:{
                    pageSize:10,//条数
                    pageNum:1,//页数
                    total:0
                },
                tatal:0,
                //新增校验规则
                rules: {
                    cardName: [
                        { validator: cardName, trigger: 'blur' }
                    ],
                    purchaseMonth: [
                        { validator: purchaseMonth, trigger: 'blur' }
                    ],
                    price: [
                        { validator: price, trigger: 'blur' }
                    ]
                },
                //修改校验规则
                rulesEdit:{
                    purchaseMonth: [
                        { validator: purchaseMonthEdit, trigger: 'blur' }
                    ],
                    price: [
                        { validator: priceEdit, trigger: 'blur' }
                    ]
                }
            }
        },
        methods:{
            //新增清空值
            handleClose(formName) {
                this.productForm.cardId=''
                this.productForm.price=''
                this.productForm.purchaseMonth=''
                this.$refs[formName].resetFields()// 重置数据，同时也取消了表单的校验 refundFormData：el-form用ref绑定的值，
            },
            //修改清空值
            handleEditClose(formName){
                this.$refs[formName].resetFields()// 重置数据，同时也取消了表单的校验 refundFormData：el-form用ref绑定的值，
            },
            // 分页
            handleSizeChange(ps) {
                this.page.pageSize=ps;
                this.getCardDetailsByPage()
                console.log(`每页 ${val} 条`);
            },
            handleCurrentChange(pn) {
                this.page.pageNum=pn;
                this.getCardDetailsByPage()
            },
            //新增选择卡类型赋值
            choiceName(cardName,id){
                this.productForm.cardName=cardName
                this.choiceCardId = id
            },
            //查询会员卡类型
            getSelectCard(){
                axios.get("http://127.0.0.1:8082/cardDetails/getSelectCard", this.cardForm).then(res=>{
                    this.selectCard = res.data.obj
                }).catch(error => {
                    this.$message.error('服务器崩溃了，请稍后再尝试使用！');
                })
            },
            //会员卡详情分页查+模糊查（会员卡名称）
            getCardDetailsByPage () {
                axios.get('http://127.0.0.1:8082/cardDetails/getCardDetailsByPage', {
                    params: {
                        cardName: this.cardName,
                        pageSize: this.page.pageSize,
                        pageNum: this.page.pageNum
                    }
                })
                    .then((res) => {
                        this.productData = res.data.content
                        this.page.total = res.data.total
                    })
            },
            //新增会员卡详情
            saveCardDetails(formName){
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        axios.post("http://127.0.0.1:8082/cardDetails/saveCardDetails",this.productForm).
                        then(res => {
                            if(res.data.obj>0){
                                this.message("恭喜你，保存数据成功！","success")
                                this.dialogFormVisible = false
                                this.productForm={
                                    cardName:'', //会员卡名称
                                    cardLevel:'',//会员卡等级
                                    cardNumber:'', //会员卡编号
                                    cardPrice:'', //会员卡价格
                                    cardExplain:'' //会员卡使用说明
                                }
                                this.getCardDetailsByPage()
                            }else{
                                this.message("对不起，保存失败！","warning")
                            }
                        }).catch(error => {
                            this.$message.error('服务器崩溃了，请稍后再尝试使用！');
                        })
                    }else {
                        return false;
                    }
                });
            },
            //修改会员卡详情
            updateCardDetails(formName){
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        axios.put("http://127.0.0.1:8082/cardDetails/updateCardDetails",this.productFormEdit)
                        .then(res=>{
                            if(res.data.code==='200'){
                            this.message("恭喜你，修改数据成功！","success")
                                    this.dialogFormVisibleUpdate = false
                                    this.productFormEdit={
                                        id:'', //会员卡id
                                        cardName:'', //会员卡名称
                                        price:'', //会员卡价格
                                        purchaseMonth:'', //会员卡月份
                                        cardId:'',
                                    }
                                    this.getCardDetailsByPage();// 重新渲染数据列表
                            }else{
                                    this.message("对不起，修改失败！","warning")
                                }
                            }).catch(error => {
                                this.$message.error('服务器崩溃了，请稍后再尝试使用！');
                        })
                    }
                });
            },
            //删除会员卡详情
            deleteCardDetails(row){
                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                }//删除提示框
                ).then(() => {
                    axios.delete("http://127.0.0.1:8082/cardDetails/deleteCardDetails?id="+row.id)
                .then(res =>{
                    if(res.data.code==='200' ){
                        this.message("恭喜你，删除成功！","success")
                        this.getCardDetailsByPage()
                    }else{
                        this.message('删除失败','warning')
                    }
                }).catch(error =>{
                        alert(error)
                })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });          
                });
            },
            //消息提示框
            message(message,type){
                this.$message({
                    message:message,
                    type: type
                });
            },
            //查看按钮回显值
            handleClick(row){
                this.dialogFormVisibleDatil = true
                this.productFormList=row
            },
            //修改按钮回显值
            handleUpdate(row){
                this.dialogFormVisibleUpdate=true
                this.productFormEdit.price = row.price
                this.productFormEdit.cardName = row.cardName
                this.productFormEdit.cardId = row.cardId
                this.productFormEdit.id = row.id
                this.productFormEdit.purchaseMonth = row.purchaseMonth
                //赋值变量
                this.updatePurchaseMont = row.purchaseMonth
                //查询卡类型
                this.getSelectCard()
            },
            //新增按钮弹出弹框
            saveCardDetail(){
                this.dialogFormVisible = true
                //查询卡类型
                this.getSelectCard()
            },
        },
        //初始化加载数据
        mounted(){
            this.getCardDetailsByPage()//分页全查+模糊查（会员卡名称）
        }, 
}
</script>
<style>
/**
        * 附件上传样式
        */
        .avatar-uploader .el-upload {
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
        }
        .avatar-uploader .el-upload:hover {
            border-color: #409EFF;
        }
        .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            line-height: 178px;
            text-align: center;
        }
        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }
        .el-icon-arrow-down {
        font-size: 12px;
     }
     .box-card {
    height: 100%;
    }
</style>